/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.facebook.fresco.helper.utils;

import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

import com.oszc.bbhmlibrary.wrapper.TextUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.UUID;

/**
 * 图像文件工具类
 *
 * @author dev
 * @since 2021-08-02
 */
public class ImageFileUtils {
    private static final double FILE_FORMAT = 1048576;
    private static final long FILE_CONSTANT = 1073741824L;
    /**
     * 本地与我们应用程序相关文件存放的根目录
     */
    private static final String ROOT_DIR_PATH = "/fresco-helper";
    /**
     * 下载图片文件存放的目录
     */
    private static final String IMAGE_DOWNLOAD_IMAGES_PATH = "/Download/Images/";

    private ImageFileUtils() {
    }

    /**
     * 获取下载图片文件存放的目录
     *
     * @param context Context
     * @return SDCard卡或者手机内存的根路径
     */
    public static String getImageDownloadDir(Context context) {
        return getRootDir(context) + IMAGE_DOWNLOAD_IMAGES_PATH;
    }

    /**
     * 获取外部存储路径
     *
     * @param context Context
     * @return SDCard卡或者手机内存的根路径
     */
    public static String getRootDir(Context context) {
        return context.getApplicationContext().getFilesDir().getPath() + ROOT_DIR_PATH;
    }

    /**
     * 随机生成一个文件，用于存放下载的图片
     *
     * @param context Context
     * @return {@link String}
     */
    public static String getImageDownloadPath(Context context) {
        String imageRootDir = getImageDownloadDir(context);
        File dir = new File(imageRootDir);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }

        String fileName = UUID.randomUUID().toString() + ".jpg";
        return dir + File.separator + fileName;
    }

    /**
     * 获取下载文件在本地存放的路径
     *
     * @param context 上下文
     * @param url url
     * @return {@link String}
     */
    public static String getImageDownloadPath(Context context, String url) {
        if (url.startsWith("/")) {
            return url;
        }

        String fileName = getFileName(url);
        String imageRootDir = getImageDownloadDir(context);
        File dir = new File(imageRootDir);
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }

        return dir + File.separator + fileName;
    }

    /**
     * 根据url获取文件名
     *
     * @param url url
     * @return {@link String}
     */
    public static String getFileName(String url) {
        String fileName = url.substring(url.lastIndexOf(File.separator) + 1);
        return fileName;
    }

    /**
     * 检查本地是否存在某个文件
     *
     * @param filePath 文件路径
     * @return boolean
     */
    public static boolean exists(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return false;
        }

        File file = new File(filePath);
        return file.exists() && file.isFile();
    }

    /**
     * 获取文件大小
     *
     * @param fileS 文件
     * @return {@link String}
     */
    public static String getFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#0.0");
        String fileSizeString;
        if (FILE_CONSTANT > fileS) {
            fileSizeString = df.format((double) fileS / FILE_FORMAT) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / FILE_CONSTANT) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 得到本地图片
     *
     * @param context 上下文
     * @param resId res id
     * @param index 指数
     * @return {@link PixelMap}
     */
    public static PixelMap getPixelMap(Context context, int resId, int index) {
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = context.getResourceManager().getResource(resId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = "image/gif";
            ImageSource imageSource = ImageSource.create(drawableInputStream, null);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredSize = new Size(0, 0);
            decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            PixelMap pixelMap = imageSource.createPixelmap(index, decodingOptions);
            return pixelMap;
        } catch (IOException | NotExistException error) {
            MLog.error("GifAbility getPixelMap IOException " + error.getLocalizedMessage());
        } finally {
            try {
                if (drawableInputStream != null) {
                    drawableInputStream.close();
                }
            } catch (IOException error) {
                MLog.error("GifAbility getPixelMap finally IOException " + error.getLocalizedMessage());
            }
        }
        return null; // 返回空
    }
}
